package com.tjhk.netty.test.client;

import com.tjhk.netty.serialize.SerializeUtil;
import com.tjhk.netty.test.model.MyHeader;
import com.tjhk.netty.test.model.MyMessage;
import com.tjhk.netty.util.ProtocolUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.time.LocalDateTime;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 当客户端连接服务器完成就会触发该方法
     *
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ByteBuf out = Unpooled.buffer(32);

        MyHeader myHeader = new MyHeader();
        myHeader.setMessageId(1);
        myHeader.setBodyLength(16);

        MyMessage message = new MyMessage();
        message.setAge(100);
        message.setName("张三");
        message.setBirthday(LocalDateTime.now());
        message.setDynamic("张三李四".getBytes(Charset.forName("GBK")));
        System.out.println(message);
        ByteBuf body = SerializeUtil.writeTo(message);
        myHeader.setBodyLength(body.readableBytes());

        out.writeBytes(SerializeUtil.writeTo(myHeader));
        out.writeBytes(body);
        System.out.println(ByteBufUtil.hexDump(out));
        ProtocolUtil.addBcc(out);
        System.out.println(ByteBufUtil.hexDump(out));
        ByteBuf allbuf = ProtocolUtil.addDelimiter(out,"##".getBytes(CharsetUtil.UTF_8));
        System.out.println(ByteBufUtil.hexDump(allbuf));
        ctx.writeAndFlush(allbuf);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelInactive：服务器断开连接");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("userEventTriggered：服务器断开连接");
    }

    //当通道有读取事件时会触发，即服务端发送数据给客户端
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("收到服务端的消息:" + buf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}